//
//  LoginService.swift
//  LeGou
//
//  Created by lxm on 2022/7/23.
//

import Foundation
class LoginService {
    private init(){}
    var verifImg = [UIImage]()
    
    var tempDidsposeBag = DisposeBag()
    
    static let shared = LoginService()
    // 是否阅读了协议
    let HAS_READ_PROTOCOL_KEY = "HAS_READ_PROTOCOL_KEY"
    
    // 行为验证码
    public func showVerifycation( vc : UIViewController,complete : @escaping ((_ success : Bool)->())) {
        loadVerifyImg {
            let ver = ActionVerifyVC()
            ver.complete = complete
            vc.present(ver, animated: true, completion: nil)
        }
    }
    
    private func loadVerifyImg(complete : @escaping ()->()) {
        tempDidsposeBag = DisposeBag()
        /// 图灵码图片
        if (verifImg.count > 0) {
            complete()
        }
        else {
            complete()
//            ZMToast.showActivity()
//            ZMLoginAPI.verifImg.rxRequest(type: [[String: String]].self).subscribe(onNext:{ [unowned self] data in
//                var tasks = [Observable<UIImage?>]()
//                for dic: [String: String] in data {
//                    tasks.append(self.imageDownload(url: dic["imgPath"]!))
//                }
//                Observable.combineLatest(tasks).subscribe(onNext:{ [unowned self] resp in
//                    self.verifImg.append(contentsOf: resp.compactMap({$0}))
//                    complete()
//                    ZMToast.hiddenActivity()
//                }).disposed(by: self.tempDidsposeBag)
//            },onError: { e in
////                ZMToast.hiddenActivity()
//                complete()
//            }).disposed(by: tempDidsposeBag)
        }
    }
    
    private func imageDownload(url : String) -> Observable<UIImage?> {
        let obable = Observable<UIImage?>.create { (obser) -> Disposable in
            ImageDownloader.default.downloadImage(with: URL(string: url)!, options: nil, progressBlock: nil) { (result) in
                switch result {
                case .success(let re):
                    obser.onNext(re.image)
                case .failure(_):
                    obser.onNext(nil)
                    break
                }
                obser.onCompleted()
            }
            
            let dis = Disposables.create {
                ImageDownloader.default.cancel(url: URL(string: url)!)
            }
            return dis
        }
        return obable
    }
    
    /// 是否阅读了协议
    /// - Returns:
    public func hasReadProtocol() -> Bool {
        if let r =  UserDefaults.standard.object(forKey: HAS_READ_PROTOCOL_KEY) as? String, r == "1" {
            return true
        } else {
            return false
        }
    }
    
    
    ///  阅读协议
    public func readProtocol() {
        UserDefaults.standard.setValue("1", forKey: HAS_READ_PROTOCOL_KEY)
    }
    
    /// 校验信息是否正确
    func checkIsInfoOk() -> Bool  {
        if let vc = checkIsInfoOkAndNextVC() {
            router.push(vc)
            return false
        } else {
            return true
        }
    }
    
    /// 校验信息是否正确,如果不正确会返回对应的控制器
    func checkIsInfoOkAndNextVC() -> UIViewController?  {
        guard let userInfo = ZMAppShareData.share.userInfo.value else {return nil}
        if userInfo.cityId == 0 {
            // 没有填写密码，没有选择城市跳转到设置密码页
            return router.viewController(for: "xm://main/Login/register")
        } else if userInfo.treeId == 0 && userInfo.darkRoom == 0 {
            // 没有 treeId
            return router.viewController(for: "xm://main/Login/invite_ode_input")
        } else {
            // 没问题可以进入app了
            return nil
        }
    }
    
    func checkLogin() -> Bool {
        if ZMAppShareData.share.isLogin {
            return true
        } else {
            router.push("xm://main/Login/index")
            return false
        }
    }
    
    func checkRealName() -> Bool {
        if ZMAppShareData.share.safeUserInfo.realName.count > 0 {
            return true
        } else {
            router.push("xm://main/Mine/real_name")
            return false
        }
    }
    
    func loginOut(_ popToRoot: Bool = true) {
        AlibcTradeUltimateSDK.sharedInstance().loginService().logout()
        ZMAppShareData.share.clearUserInfo()
        if popToRoot {
            AppHelper.currentNav()?.popToRootViewController(animated: true)
        }
    }
    
}

